package cn.edu.zjicm.wordsnet_d.data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Html;
import android.util.Log;
import android.text.Spanned;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.data.metadata.ChildItem;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;

public class OneWord implements ChildItem<Integer>, Comparable<OneWord>, Serializable, Parcelable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3492923448498379093L;

	public static final int DEGREE_UNLEARN = 0;
	public static final int DEGREE_UNFAMILIAR = 10;
	// public static final int DEGREE_MIDFAMILIAR = 20;
	public static final int DEGREE_FAMILIAR = 20;

	/*
	 * 未学 词义熟悉度0 生词-熟悉度1 词义熟悉度10-29 生词-熟悉度2 词义熟悉度30-39 生词-熟悉度3 词义熟悉度40-49
	 * 生词-熟悉度4 词义熟悉度50-59 熟词(熟悉度5) 词义熟悉度60 太简单(熟悉度6) 熟悉度1000
	 */

	public static final int SENSE_DEGREE_UNLEARN_TYPE = 0;
	public static final int SENSE_DEGREE_UNFAMILIAR1_TYPE = 1;
	public static final int SENSE_DEGREE_UNFAMILIAR2_TYPE = 2;
	public static final int SENSE_DEGREE_UNFAMILIAR3_TYPE = 3;
	public static final int SENSE_DEGREE_UNFAMILIAR4_TYPE = 4;
	public static final int SENSE_DEGREE_FAMILIAR_TYPE = 5;
	public static final int SENSE_DEGREE_TOO_EASY_TYPE = 6;

	public static final int SENSE_DEGREE_UNLEARN = 0;
	public static final int SENSE_DEGREE_UNFAMILIAR0 = 10;
	public static final int SENSE_DEGREE_UNFAMILIAR1 = 20;
	public static final int SENSE_DEGREE_UNFAMILIAR2 = 30;
	public static final int SENSE_DEGREE_UNFAMILIAR3 = 40;
	public static final int SENSE_DEGREE_UNFAMILIAR4 = 50;
	public static final int SENSE_DEGREE_FAMILIAR = 60;
	public static final int SENSE_DEGREE_TOO_EASY = 1000;
	public static final int SENSE_DEGREE_TOO_EASY_FROM_CONSOLIDATE = 1100;

	private int index_word_id;
	private String lemma;
	private String lemma_mark;
	private String senses_senior;
	private String senses_sch;
	private String phonetic;
	private int lemma_type;
	private int level_min;
	private String aff_content;
	private int haveaudio_us;
	private int time_set;
	private int degree_fm;
	private int voice_degree_fm;
	private int last_huanbo_time;
	private int sense_degree_fm;
	private int last_test_time;
	private int time_forget;
	private int consolidate_next_time;
	private int difficulty;

	private int consolidate_test_count;
	private int lock_time;

	private int book_id;
	private int ind;

	private int repeatingCount; // 复读的次数

	public int getReadTimeNotRepeat() {
		return readTimeNotRepeat;
	}

	public void setReadTimeNotRepeat(int readTimeNotRepeat) {
		this.readTimeNotRepeat = readTimeNotRepeat;
	}

	public void addReadTimeNotRepeat() {
		readTimeNotRepeat++;
	}

	private int repeateTime; // 应当重复出现的次数
	private int readTime; // 已重复出现的次数
	private int readTimeNotRepeat; // 已重复出现的次数

	private int groupBy;
	public static final int GROUP_BY_UNIT = 0;
	public static final int GROUP_BY_DATE = 1;
	
	public static final int LEMMA_TYPE_WORD = 1;           //单词
	public static final int LEMMA_TYPE_PHRASE = 2;         //短语
	public static final int LEMMA_TYPE_COLLOCATION = 3;    //搭配

	public OneWord() {
	}

	public OneWord(Cursor c) {
		this(c.getInt(c.getColumnIndex("index_word_id")), c.getString(c.getColumnIndex("lemma")), c.getString(c.getColumnIndex("lemma_mark")), c.getString(c.getColumnIndex("senses_senior")), c
				.getString(c.getColumnIndex("senses_sch")), c.getString(c.getColumnIndex("phonetic")), c.getInt(c.getColumnIndex("lemma_type")), c.getInt(c.getColumnIndex("level_min")), c.getString(c
				.getColumnIndex("aff_content")), c.getInt(c.getColumnIndex("haveaudio_us")), c.getInt(c.getColumnIndex("time_set")), c.getInt(c.getColumnIndex("degree_fm")), c.getInt(c
				.getColumnIndex("voice_degree_fm")), c.getInt(c.getColumnIndex("last_huanbo_time")), c.getInt(c.getColumnIndex("sense_degree_fm")), c.getInt(c.getColumnIndex("last_test_time")), c
				.getInt(c.getColumnIndex("time_forget")), c.getInt(c.getColumnIndex("time_lock")), c.getInt(c.getColumnIndex("next_test_time")), c.getInt(c.getColumnIndex("test_count")), c.getInt(c
				.getColumnIndex("difficulty")));
	}

	public OneWord(Cursor c, boolean onlyWordInfo) {
		this(c.getInt(c.getColumnIndex("index_word_id")), c.getString(c.getColumnIndex("lemma")), c.getString(c.getColumnIndex("lemma_mark")), c.getString(c.getColumnIndex("senses_senior")), c
				.getString(c.getColumnIndex("senses_sch")), c.getString(c.getColumnIndex("phonetic")), c.getInt(c.getColumnIndex("lemma_type")), c.getInt(c.getColumnIndex("level_min")), c.getString(c
				.getColumnIndex("aff_content")), c.getInt(c.getColumnIndex("haveaudio_us")));
	}

	public OneWord(Cursor c, int book_id) {
		this(c);
		this.book_id = book_id;
	}

	public OneWord(int index_word_id, String lemma, String lemma_mark, String senses_senior, String senses_sch, String phonetic, int lemma_type, int level_min, String aff_content, int haveaudio_us,
			int time_set, int degree_fm, int voice_degree_fm, int last_huanbo_time, int sense_degree_fm, int last_test_time, int time_forget, int time_lock, int next_test_time, int test_count,
			int difficulty) {
		this.index_word_id = index_word_id;
		this.lemma = lemma;
		this.lemma_mark = lemma_mark;
		this.senses_senior = senses_senior.replace("#n", "  ");
		this.senses_sch = senses_sch;
		this.phonetic = phonetic;
		this.lemma_type = lemma_type;
		this.level_min = level_min;
		this.aff_content = aff_content;
		this.haveaudio_us = haveaudio_us;
		this.time_set = time_set;
		this.degree_fm = degree_fm;
		this.voice_degree_fm = voice_degree_fm;
		this.last_huanbo_time = last_huanbo_time;
		this.sense_degree_fm = sense_degree_fm;
		this.last_test_time = last_test_time;
		this.time_forget = time_forget;
		this.consolidate_next_time = next_test_time;
		this.consolidate_test_count = test_count;
		this.lock_time = time_lock;
		this.difficulty = difficulty;
	}

	public OneWord(int index_word_id, String lemma, String lemma_mark, String senses_senior, String senses_sch, String phonetic, int lemma_type, int level_min, String aff_content, int haveaudio_us) {
		this.index_word_id = index_word_id;
		this.lemma = lemma;
		this.lemma_mark = lemma_mark;
		this.senses_senior = senses_senior.replace("#n", "  ");
		this.senses_sch = senses_sch;
		this.phonetic = phonetic;
		this.lemma_type = lemma_type;
		this.level_min = level_min;
		this.aff_content = aff_content;
		this.haveaudio_us = haveaudio_us;
	}

	public int getSense_degree_fm() {
		return sense_degree_fm;
	}

	public String getSense_degree_fm_str() {
		Date d = new Date((long) getLast_test_time() * 60 * 1000);
		java.text.DateFormat df = new java.text.SimpleDateFormat("yy-MM-dd HH:mm");
		return (sense_degree_fm + 1) + " " + df.format(d);
	}

	public void setSense_degree_fm(int sense_degree_fm) {
		this.sense_degree_fm = sense_degree_fm;
	}

	/*
	 * public static OneWord makeTestData() { return new OneWord(1002, 102,
	 * "zeny", "adf fdf", "['kamp(e)rel]", 1, 0, 0, 0, 0, 0, 0); }
	 */

	public int getIndex_word_id() {
		return index_word_id;
	}

	public void setIndex_word_id(int index_word_id) {
		this.index_word_id = index_word_id;
	}

	public int getUnit_id() {
		// return unit_id;
		return ind;
	}

	public int getRepeatingCount() {
		return repeatingCount;
	}

	public void setRepeatingCount(int repeatingCount) {
		this.repeatingCount = repeatingCount;
	}

	/**
	 * 英文单词
	 * 
	 * @return
	 */
	public String getLemma() {
		// if(getSyllableCount() >= 2) {
		// LogUtil.e(lemma, Arrays.asList(getSyllables()).toString());
		// LogUtil.e(lemma, getDisturbSyllables().toString());
		// }
		return lemma;
	}

	public void setLemma(String lemma) {
		this.lemma = lemma;
	}

	public String getPhonetic() {
		return phonetic;
	}

	public void setPhonetic(String phonetic) {
		this.phonetic = phonetic;
	}

	public String getSensesSenior() {
		return senses_senior;
	}

	public int getLemma_type() {
		return lemma_type;
	}

	public void setLemma_type(int lemma_type) {
		this.lemma_type = lemma_type;
	}

	/**
	 * 中文意思
	 * 
	 * @param senses
	 */
	public void setSensesSenior(String senses_senior) {
		this.senses_senior = senses_senior;
	}

	public String getSenses_sch() {
		return senses_sch;
	}

	public void setSenses_sch(String senses_sch) {
		this.senses_sch = senses_sch;
	}

	public String getAff_content() {
		return aff_content;
	}

	public void setAff_content(String aff_content) {
		this.aff_content = aff_content;
	}

	public String getLemma_mark() {
		return lemma_mark;
	}

	public void setLemma_mark(String lemma_mark) {
		this.lemma_mark = lemma_mark;
	}

	/* 单词分割成几个音节 */
	public int getSyllableCount() {
		return lemma_mark.split("/").length;
	}

	/* 单词分割成的音节 */
	public String[] getSyllables() {
		return lemma_mark.split("/");
	}

	/* 单词分割成的音节,用不同颜色表示 */
	public Spanned getSyllablesSpan(Context context) {
		String[] syllables = getSyllables();
		if (syllables[0].length() == 0)
			syllables[0] = getLemma();
		int color;
		String lemmaHtml = "";
		for (int i = 0; i < syllables.length; i++) {
			if (i % 2 == 0) {
				color = context.getResources().getColor(R.color.text_color_for_syllable_green);
			} else {
				color = context.getResources().getColor(R.color.text_color_for_syllable_red);
			}
			lemmaHtml += "<font color='" + color + "'>" + syllables[i] + "</font>";
		}
		return Html.fromHtml(lemmaHtml);
	}

	Map<Character, Character> map = new HashMap<Character, Character>() {
		{
			put('a', 'e');
			put('e', 'i');
			put('i', 'e');
			put('o', 'u');
			put('u', 'o');
			put('m', 'n');
			put('n', 'm');
			put('b', 'p');
			put('p', 'b');
			put('d', 't');
			put('t', 'd');
			put('s', 'z');
			put('z', 's');
			put('k', 'g');
			put('g', 'k');
			put('f', 'v');
			put('v', 'f');
			put('l', 'r');
			put('r', 'l');
			put('j', 'g');
			put('w', 'y');
			put('x', 'y');
			put('y', 'w');
			put('c', 'k');
			put('q', 'w');
			put('h', 'g');
		}
	};

	/* 音节干扰项, 2-3个音节：2个干扰项(元音2，辅音0)；4-5个音节：3个干扰项(元音2，辅音1)；6个音节及以上：4个干扰项(元音2，辅音2) */
	public List<String> getDisturbSyllables() {
		List<String> list = Arrays.asList(getSyllables()); // 音节
		Collections.sort(list, new SortSyllables());

		List<String> disturbList = new ArrayList<String>(); // 干扰项

		int vowelDisturbCount = 2;

		int consonantiDisturbCount = 0; // 辅音干扰项个数，4-5个音节，个数为1；6个音节及以上，个数为2；其他为0
		if (list.size() >= 4 && list.size() <= 5)
			consonantiDisturbCount = 1;
		else if (list.size() >= 6)
			consonantiDisturbCount = 2;

		// 生成元音干扰项
		for (int i = 0; vowelDisturbCount > 0 && i < list.size(); i++) {
			String str = createVowelDisturbSyllable(list.get(i));
			if (str != null) {
				disturbList.add(str);
				vowelDisturbCount--;
			}
		}

		// 生成辅音干扰项
		for (int i = list.size() - 1; consonantiDisturbCount > 0 && i >= 2; i--) {
			if (list.get(i).length() == 1) // 跳过长度为1的音节
				continue;
			disturbList.add(createConsonantiDisturbSyllable(list.get(i)));
			consonantiDisturbCount--;
		}
		return disturbList;
	}

	String createVowelDisturbSyllable(String str) {
		char c = 0;
		int i;
		for (i = 0; i < str.length(); i++) {
			c = Character.toLowerCase(str.charAt(i));
			if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
				break;
		}
		if (i >= str.length())
			return null;
		c = map.get(c);
		if (Character.isUpperCase(str.charAt(i)))
			c = Character.toUpperCase(c);
		return (i > 0 ? str.substring(0, i) : "") + c + ((i + 1) < str.length() ? str.substring(i + 1) : "");
	}

	String createConsonantiDisturbSyllable(String str) {
		char c = 0;
		int i;
		for (i = 0; i < str.length(); i++) {
			c = Character.toLowerCase(str.charAt(i));
			if (!(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'))
				break;
		}
		c = map.get(c);
		if (Character.isUpperCase(str.charAt(i)))
			c = Character.toUpperCase(c);
		return (i > 0 ? str.substring(0, i) : "") + c + ((i + 1) < str.length() ? str.substring(i + 1) : "");
	}

	// 按字符串长度递增排序，但长度为1的排在最后
	class SortSyllables implements Comparator<String> {
		public int compare(String word1, String word2) {
			if (word1.length() == 1 && word2.length() > 1)
				return 1;
			else if (word1.length() > 1 && word2.length() == 1)
				return -1;
			else
				return word1.length() - word2.length();
		}
	}

	/* 音节干扰项, 随机 */
	// public List<String> getDisturbSyllables(){
	// List<String> list = new ArrayList<String>();
	// String syllabes[] = getSyllables();
	// for(int i = 0; i < syllabes.length; i++){
	// if(syllabes[i].length() >= 2) {
	// char a = syllabes[i].charAt(1);
	// while(a == syllabes[i].charAt(1))
	// a = (char) ('a' + (int)(Math.random() * 26));
	// list.add(syllabes[i].substring(0, 1) + a + (syllabes[i].length() > 2 ?
	// syllabes[i].substring(2) : ""));
	// }
	// }
	// Collections.shuffle(list);
	// int syllableCount = getSyllableCount();
	// if(syllableCount >= 2 && syllableCount <= 3)
	// if(list.size() > 2)
	// list = list.subList(0, 2);
	// else if(syllableCount >= 4){
	// if(list.size() > 3)
	// list = list.subList(0, 3);
	// }
	// return list;
	// }

	public int getLevel_min() {
		return level_min;
	}

	public void setLevel_min(int level_min) {
		this.level_min = level_min;
	}

	public int getTime_set() {
		return time_set;
	}

	public void setTime_set(int time_set) {
		this.time_set = time_set;
	}

	public int getDegree_fm() {
		return degree_fm;
	}

	public void setDegree_fm(int degree_fm) {
		this.degree_fm = degree_fm;
	}

	public int haveAudio() {
		return haveaudio_us;
	}

	public String toString() {
		return lemma + "\n" + "音标 " + phonetic + "\n" + "释义 " + senses_senior + "\n" +
		// "例句 "+exa_native + "\n" +
		// exa_cn + "\n" +
		// "词根 "+affix + "\n" +
				"学习时间 " + time_set + "\n" + "熟悉度 " + degree_fm + "\n";
	}

	public void setSenseDegree_fmWhenRightAnswer() {
		int temp = sense_degree_fm;
		sense_degree_fm += 1;
		Log.e("熟悉度变化", this.lemma + ":" + temp + "-" + sense_degree_fm);
	}

	public void setSenseDegree_fmWhenWrongAnswer() {
		int temp = sense_degree_fm;
		sense_degree_fm -= 1;
		if (sense_degree_fm < 2) {
			sense_degree_fm = 2;
		}
		// Log.e("熟悉度减不低于2",this.getLemma());
		Log.e("熟悉度变化", this.lemma + ":" + temp + "-" + sense_degree_fm);
	}

	@Override
	public int compareTo(OneWord another) {
		// TODO Auto-generated method stub
		// 排序
		// return this.lemma.compareTo(another.lemma);
		return this.ind - another.ind;
	}

	@Override
	public Integer getGroupBy() {
		// TODO Auto-generated method stub
		/*
		 * if(groupBy==OneWord.GROUP_BY_UNIT) return Integer.valueOf(unit_id);
		 * else return Integer.valueOf(time_set);
		 */
		return Integer.valueOf(time_set);
	}

	public void setGroupBy(int groupBy) {
		this.groupBy = groupBy;
	}

	public int getDegree() {
		switch (getDegree_fm()) {
		case 0:
			return OneWord.DEGREE_UNLEARN;
		case 10:
			return OneWord.DEGREE_UNFAMILIAR;
		case 20:
			return OneWord.DEGREE_FAMILIAR;
		default:
			return OneWord.DEGREE_UNLEARN;
		}
	}

	// 用于测试时计数，答对一次减1，减为0后不用再测试
	private int testCount = 2;

	public void testCorrect() {
		testCount--;
	}

	public boolean isFinishTest() {
		return testCount == 0;
	}

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void writeToParcel(Parcel parcel, int arg1) {
		// TODO Auto-generated method stub
		parcel.writeInt(this.index_word_id);
		parcel.writeInt(this.ind);
		parcel.writeString(this.lemma);
		parcel.writeString(this.senses_senior);
		parcel.writeString(this.senses_sch);
		parcel.writeString(this.phonetic);
		parcel.writeString(this.aff_content);
		parcel.writeInt(this.haveaudio_us);
		parcel.writeInt(this.time_set);
		parcel.writeInt(this.degree_fm);
		parcel.writeInt(this.voice_degree_fm);
		parcel.writeInt(this.last_huanbo_time);
		parcel.writeInt(this.sense_degree_fm);
		parcel.writeInt(this.last_test_time);
	}

	public void setRepeateTime(int repeateTime) {
		this.repeateTime = repeateTime;
	}

	public int getRepeateTime() {
		return repeateTime;
	}

	public void setReadTime(int readTime) {
		this.readTime = readTime;
	}

	public int getReadTime() {
		return readTime;
	}

	public void setVoice_degree_fm(int voice_degree_fm) {
		this.voice_degree_fm = voice_degree_fm;
	}

	public int getVoice_degree_fm() {
		return voice_degree_fm;
	}

	public void setLast_huanbo_time(int last_huanbo_time) {
		this.last_huanbo_time = last_huanbo_time;
	}

	public int getLast_huanbo_time() {
		return last_huanbo_time;
	}

	public void setLast_test_time(int last_test_time) {
		this.last_test_time = last_test_time;
	}

	public int getForget_time() {
		return time_forget;
	}

	public int getLast_test_time() {
		return last_test_time;
	}

	public boolean isInclude() {
		return true;
	}

	public int getBook_id() {
		return book_id;
	}

	public void setBook_id(int book_id) {
		this.book_id = book_id;
	}

	public boolean isDifficulty() {
		if (1 == this.difficulty)
			return true;
		else
			return false;
	}

	public void setDifficulty(boolean isTrue, Context context) {
		if (isTrue) {
			this.difficulty = 1;
		} else {
			this.difficulty = 0;
		}
		WordFactory.getInstance(context).updateDifficulty(this.difficulty,index_word_id);
	}

	public String getBookName() {
		String str = "";
		if (book_id == 0) {
			str = "低频单词";
		} else if (book_id == AppPreference.Book.BOOK_ID[6]) {
			str = "高中单词";
		} else if (book_id == AppPreference.Book.BOOK_ID[0]) {
			str = "四级单词";
		} else if (book_id == AppPreference.Book.BOOK_ID[1]) {
			str = "六级单词";
		} else if (book_id == AppPreference.Book.BOOK_ID[2]) {
			str = "考研单词";
		} else if (book_id == AppPreference.Book.BOOK_ID[0] + AppPreference.Book.BOOK_ID[1]) {
			str = "四级,六级单词";
		} else if (book_id == AppPreference.Book.BOOK_ID[0] + AppPreference.Book.BOOK_ID[2]) {
			str = "四级,考研单词";
		} else if (book_id == AppPreference.Book.BOOK_ID[1] + AppPreference.Book.BOOK_ID[2]) {
			str = "六级,考研单词";
		} else if (book_id == AppPreference.Book.BOOK_ID[0] + AppPreference.Book.BOOK_ID[1] + AppPreference.Book.BOOK_ID[2]) {
			str = "四级,六级,考研单词";
		}
		return str;
	}

	// public static final Parcelable.Creator<OneWord> CREATOR = new
	// Creator<OneWord>() {
	// @Override
	// public OneWord[] newArray(int i) {
	// return new OneWord[i];
	// }
	//
	// @Override
	// public OneWord createFromParcel(Parcel parcel) {
	// // TODO Auto-generated method stub
	// return new OneWord(parcel.readInt(), parcel.readString(),
	// parcel.readString(), parcel.readString(), parcel.readString(),
	// parcel.readString(), parcel.readInt(), parcel.readInt(),
	// parcel.readString(), parcel.readInt(), parcel.readInt(),
	// parcel.readInt(), parcel.readInt(), parcel.readInt(), parcel.readInt(),
	// parcel.readInt(), parcel.readInt(),
	// parcel.readInt(), parcel.readInt(), parcel.readInt(), parcel.readInt());
	// }
	// };

	public boolean equals(OneWord w) {
		if (this.index_word_id == w.getIndex_word_id())
			return true;
		else
			return false;
	}

	public boolean showAffix(Context context) {
		return isShowAffixTab() || WordFactory.getInstance(context).getWordRoot(getIndex_word_id()) != null;
	}

	public boolean isShowAffixTab() {
		return (getAff_content() != null && getAff_content().length() > 0);
	}

	public boolean showSameShape(Context context, boolean testMode) {
		return WordFactory.getInstance(context).getSameShape(index_word_id, lemma_type, testMode).size() > 0;
	}

	public int getConsolidateNextTime() {
		return consolidate_next_time;
	}

	public void setConsolidateNextTime(int consolidate_next_time) {
		this.consolidate_next_time = consolidate_next_time;
	}

	public int getConsolidateTestCount() {
		return consolidate_test_count;
	}

	public void setConsolidateTestCount(int consolidate_test_count) {
		this.consolidate_test_count = consolidate_test_count;
	}

}
